import React, { useState } from 'react';
import { axconst } from '@/shared/axconst';

export const Check: React.FC<any> = props => {
  let { selectedRows = [], ...restProps } = props;
  const {
    WrappedComponent,
    checkboxType = 'checkbox',
    onSelectRow,
    checkboxFixed = true,
    getCheckboxProps,
    selectOnClick = true,
    ...rest
  } = restProps;

  /** 选中行的keys */
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  /** 点击checkbox选中处理函数 */
  const handleRowSelectChange = (selectedRowKeys: any, selectedRows: any) => {
    if (onSelectRow) {
      onSelectRow(selectedRows);
    }

    setSelectedRowKeys(selectedRowKeys);
  };

  /** 点击行选中处理函数 */
  const handleSelectRow = ({ record }: any) => {
    let keys = selectedRowKeys.slice();
    if (getCheckboxProps) {
      const { disabled } = getCheckboxProps(record);
      /** 如果复选框无效，直接返回 */
      if (disabled === true) {
        return;
      }
    }

    if (keys.indexOf(record.id as never) >= 0) {
      keys.splice(keys.indexOf(record.id as never), 1);
      selectedRows.splice(selectedRows.indexOf(record), 1);
    } else {
      keys.push(record.id as never);
      selectedRows.push(record);
    }
    if (checkboxType === 'radio') {
      keys = [];
      selectedRows = [];
      keys.push(record.id as never);
      selectedRows.push(record);
    }
    if (onSelectRow) {
      onSelectRow(selectedRows);
    }
    setSelectedRowKeys(keys);
  };

  /** 复选框 */
  const rowSelection = checkboxType
    ? {
        selectedRowKeys,
        onChange: handleRowSelectChange,
        /** 选择框的默认属性配置 */
        getCheckboxProps: getCheckboxProps,
        fixed: checkboxFixed,
        type: checkboxType,
        columnWidth: axconst.width.checkbox,
      }
    : null;

  return (
    <WrappedComponent
      rowSelection={rowSelection}
      onRow={(record: any) => ({
        // onDoubleClick: () => {
        //     if (onDoubleClick) {
        //         onDoubleClick(record);
        //     }
        // },
        onClick: (event: any) => {
          if (selectOnClick === true) handleSelectRow({ record, event });
        },
      })}
      {...rest}
    />
  );
};
